<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="search-container">
        <el-input
          v-model="listQuery.userName"
          placeholder="账户名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button
          class="filter-item"
          type="primary"
          @click="handleFilter"
        >
          {{ $t("table.search") }}
        </el-button>
      </div>
      <el-button class="filter-item" type="primary" @click="handleAdd">
        新增用户
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 + 1 * (listQuery.current - 1) * listQuery.size }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="账号名称">
        <template slot-scope="scope">
          <span>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="账号类型">
        <template slot-scope="scope">
          <el-dropdown trigger="click" @command="changeType(scope.row, $event)">
            <span style="cursor: pointer;color: #409EFF">
              {{ scope.row.type === 1 ? '管理员' : '普通用户' }}<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="1">管理员</el-dropdown-item>
              <el-dropdown-item :command="2">普通用户</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="账号状态">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status"
            :active-value="1"
            :inactive-value="2"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="180px" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="120">
        <template slot-scope="scope">
          <el-popconfirm title="确认删除吗？" @onConfirm="onDelete(scope.row.id)">
            <el-button
              slot="reference"
              type="danger"
              size="small"
            >
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :visible.sync="dialogVisible" width="320px" title="新增账户">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="账号名称" props="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="账号类型" prop="type">
          <el-select
            v-model="temp.type"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in types"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" props="status">
          <el-switch
            v-model="temp.status"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">
          {{ $t('permission.cancel') }}
        </el-button>
        <el-button type="primary" @click="checkUserName">
          {{ $t('permission.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { registry, checkUserName, accountList, accountUpdate, accountDelete } from '@/api/user'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        current: 1,
        size: 10,
        userName: '',
        type: undefined,
        status: undefined
      },
      types: [
        {
          key: 1,
          label: '管理员'
        },
        {
          key: 2,
          label: '普通用户'
        }
      ],
      temp: {
        id: undefined,
        userName: '',
        type: 1,
        status: 1
      },
      rules: {
        userName: [{ required: true, message: '账户名称不能为空', trigger: 'blur' }]
      },
      dialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      accountList(this.listQuery).then((response) => {
        const { records, total } = response.object
        this.list = records || []
        this.total = total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    handleAdd() {
      this.temp = {
        id: undefined,
        userName: '',
        type: 1,
        status: 1
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    checkUserName() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.append('userName', this.temp.userName)
          checkUserName(formData).then(res => {
            if (res.object) {
              this.$notify({
                title: '错误',
                message: '账号已存在',
                type: 'error',
                duration: 2000
              })
            } else {
              this.registry()
            }
          })
        }
      })
    },
    registry() {
      registry(this.temp).then(() => {
        this.handleFilter()
        this.dialogVisible = false
        this.$notify({
          title: '成功',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    changeStatus(row) {
      const data = {
        accountId: row.id,
        status: row.status === 1 ? 2 : 1
      }

      accountUpdate(data).then(() => {
        row.status = row.status === 1 ? 2 : 1
        this.$notify({
          title: '成功',
          message: '账号状态修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    changeType(row, type) {
      if (row.type === type) return
      const data = {
        accountId: row.id,
        type: type
      }

      accountUpdate(data).then(() => {
        row.type = type
        this.$notify({
          title: '成功',
          message: '账号类型修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    onDelete(id) {
      const formData = new FormData()
      formData.append('accountId', id)
      accountDelete(formData).then(() => {
        this.handleFilter()
        this.list = this.list.filter(res => res.id !== id)
        this.total--
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
